package com.itheima.reggie.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 支付宝支付
 */
@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController {

    //支付成功后要跳转的页面
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Autowired
    private OrderService orderService;


    /**
     * 支付宝支付
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/confirm" , produces = {"text/html;charset=UTF-8"})
    public Object confirm(Long id) throws Exception {

        //根据订单id查询订单详情
        Orders orders = orderService.getById(id);
        //生成订单名称
        String orderName = "瑞吉外卖，订单号：" + id + "，收货人为：" + orders.getConsignee();

        //调用sdk，发起支付
        AlipayTradePagePayResponse response = Factory.Payment
                //选择网页支付平台
                .Page()
                //调用支付方法，设置订单名称、我们自己系统中的订单号、金额、回调页面
                .pay(orderName,       //订单名称
                        id.toString(),     //订单号
                        orders.getAmount().toString(),       //订单金额
                        returnUrl);

        //这里的response.body，就是一个可以直接加载的html片段，
        // 这里为了简单我直接返回这个片段，前端直接
        return response.body;
    }

    /**
     * 支付成功后支付宝回调接口
     * @param request
     * @return
     */
    @PostMapping("/fallback")
    public void fallback (HttpServletRequest request) {
        Map map = request.getParameterMap();
        //取出订单号
        String[]numbers=(String[])map.get("out_trade_no");
        String number=numbers[0];
        //根据订单号查询
        Orders order=orderService.getById(number);
        log.info("-----订单"+number+"支付成功，进入回调-----");
        //修改订单状态
        order.setStatus(2);
        orderService.updateById(order);
    }
}
